﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Admin.Models;
using AOP.Filter.Result;
using CacheService.Standard;
using Common.Standard;
using Microsoft.AspNetCore.Mvc;
using MODEL.Model;
using SERVICE.Admin.IService;

namespace Admin.Controllers.System
{
    [Description("系统设置")]
    public class MenuController : Controller
    {
        ICache cache;
        ISyetemService syetemService;
        public MenuController(ICache cache, ISyetemService syetemService)
        {
            this.cache = cache;
            this.syetemService = syetemService;
        }
        [Description("菜单设置"), Native]
        public IActionResult Index()
        {
            return View();
        }
        [Description("菜单设置"), HttpPost]
        public bool SaveMenu(IList<string> paths)
        {
            var views = cache.get<List<Jurisdict>>("views").ToList();
            var groups = views.Where(x => x.jurisdictViews.Where(c => c.actionApis.Where(s => paths.Contains(s.path)).Any()).Any()).Distinct().ToList();
            var list = new List<SystemMenu>();
            foreach (var group in groups)
            {
                var menu = list.Where(x => x.name == group.groupName).FirstOrDefault();
                if (menu == null)
                {
                    menu = new SystemMenu();
                    menu.name = group.groupName;
                    list.Add(menu);
                }
                var ps = new List<SystemMenuPath>();
                group.jurisdictViews.ForEach(c => c.actionApis.ForEach(a => ps.Add(new SystemMenuPath
                {
                    name = a.name,
                    path = a.path
                })));
                menu.SystemMenuPaths.AddRange(ps.Where(x => paths.Contains(x.path)).ToList());
            }
            return syetemService.SaveMenu(list);
        }
        [Description("菜单设置"), HttpGet]
        public object GetMenu()
        {
            var list = new List<string>();
            syetemService.GetMenu().ForEach(x => x.SystemMenuPaths.ForEach(c => list.Add(c.path)));
            return list;
        }
    }
}